package com.bkgy.modular.tbdsjrawcheckc621.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bkgy.excelhandle.PlanExcelHandlerImpl;
import com.bkgy.modular.qms.dao.QmsCurveDataMongoDao;
import com.bkgy.modular.qms.entity.QmsCurveDataMongo;
import com.bkgy.modular.tbdsjrawcheckc621.dao.TbDsjRawcheckC621Dao;
import com.bkgy.modular.tbdsjrawcheckc621.entity.ExportTbDsjRawcheckC621;
import com.bkgy.modular.tbdsjrawcheckc621.entity.JTbDsjRawcheckC621;
import com.bkgy.modular.tbdsjrawcheckc621.entity.TbDsjRawcheckC621;
import com.bkgy.modular.tbdsjrawcheckc621.service.TbDsjRawcheckC621Service;
import com.bkgy.sys.common.entity.ResultData;
import com.bkgy.util.CodiUtil;
import com.bkgy.util.ExcelUtilsPOI;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 1720酸轧原料审核表接口具体实现类
* @author  生成器生成
* @date 2022-10-18 10:08:09
*/
@Service
public class TbDsjRawcheckC621ServiceImpl implements TbDsjRawcheckC621Service {

	@Autowired
	private TbDsjRawcheckC621Dao tbDsjRawcheckC621Dao;

	@Resource
	private QmsCurveDataMongoDao qmsCurveDataMongoDao;

	@Resource
	private MongoTemplate mongoTemplate;

	/**
     * 添加记录
     * @param data json字符串
     * @param userId 用户id
     * @param sname 用户姓名
     */
	public ResultData insertDataTbDsjRawcheckC621(String data,Long userId,String sname){
		try{
			JTbDsjRawcheckC621 jtbDsjRawcheckC621 = JSON.parseObject(data,JTbDsjRawcheckC621.class);
    		TbDsjRawcheckC621 tbDsjRawcheckC621 = jtbDsjRawcheckC621.getTbDsjRawcheckC621();
    		CodiUtil.newRecord(userId,sname,tbDsjRawcheckC621);
            tbDsjRawcheckC621Dao.insertDataTbDsjRawcheckC621(tbDsjRawcheckC621);
            return ResultData.ResultDataSuccessSelf("添加数据成功", null);
    	}catch(Exception e){
    		e.printStackTrace();
    		return ResultData.ResultDataFaultSelf("添加失败，错误信息为" + e.getMessage(), null);
    	}
	};

	/**
	 * 根据主键删除对象
	 * @param indocno  对象主键
	 * */
	public ResultData deleteDataTbDsjRawcheckC621One(Long indocno){
		try {
            tbDsjRawcheckC621Dao.deleteDataTbDsjRawcheckC621One(indocno);
             return ResultData.ResultDataSuccessSelf("删除数据成功", null);
        } catch (Exception e) {
        	e.printStackTrace();
        	return ResultData.ResultDataFaultSelf("删除失败,失败信息为" + e.getMessage(), null);
        }
	};

	/**
     * 根据主键字符串删除多个对象
     * @param str_id 对象主键字符串
     */
    public ResultData deleteDataTbDsjRawcheckC621Many(String str_id) {
        try {
        	String sql = "delete tb_dsj_rawcheck_c621 where indocno in(" + str_id +")";
            tbDsjRawcheckC621Dao.deleteDataTbDsjRawcheckC621Many(sql);
            return ResultData.ResultDataSuccessSelf("删除数据数据成功", null);
        } catch (Exception e) {
        	e.printStackTrace();
        	return ResultData.ResultDataFaultSelf("删除失败,失败信息为" + e.getMessage(), null);
        }
    }

	/**
     * 修改记录
     * @param userId 用户id
     * @param sname 用户姓名
     * @param data sysUser 对象实体
     */
	public ResultData updateDataTbDsjRawcheckC621(String data,Long userId,String sname){
		try {
			JTbDsjRawcheckC621 jtbDsjRawcheckC621 = JSON.parseObject(data,JTbDsjRawcheckC621.class);
    		TbDsjRawcheckC621 tbDsjRawcheckC621 = jtbDsjRawcheckC621.getTbDsjRawcheckC621();
        	CodiUtil.editRecord(userId,sname,tbDsjRawcheckC621);
            tbDsjRawcheckC621Dao.updateDataTbDsjRawcheckC621(tbDsjRawcheckC621);
            return ResultData.ResultDataSuccessSelf("修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("修改失败,失败信息为" + e.getMessage(), null);
        }
	};

	/**
     * 分页查看记录
     * @param data 分页参数字符串
     */
    public ResultData findDataTbDsjRawcheckC621ByPage(String data) {
        try {
        	JTbDsjRawcheckC621 jtbDsjRawcheckC621 = JSON.parseObject(data, JTbDsjRawcheckC621.class);
        	JSONObject jsonObject  = null;
        	Integer pageIndex = jtbDsjRawcheckC621.getPageIndex();
        	Integer pageSize = jtbDsjRawcheckC621.getPageSize();

        	if(null == pageIndex || null == pageSize){
        		return ResultData.ResultDataFaultSelf("分页参数没有传", null);
        	}

        	if(null!=jtbDsjRawcheckC621.getCondition()){
				jsonObject  = JSON.parseObject(jtbDsjRawcheckC621.getCondition().toString());
			}

			String hot_coil_id = null;//热卷号
			if (!StringUtils.isEmpty(jsonObject.get("hot_coil_id"))) {
				hot_coil_id = jsonObject.get("hot_coil_id").toString();
			}
			String steelgrade = null;//钢牌号
			if (!StringUtils.isEmpty(jsonObject.get("steelgrade"))) {
				steelgrade = jsonObject.get("steelgrade").toString();
			}
			String fin_grade = null;//等级
			if (!StringUtils.isEmpty(jsonObject.get("fin_grade"))) {
				fin_grade = jsonObject.get("fin_grade").toString();
			}


			String dbegin = null; //开始时间
			if (StringUtils.hasText(jsonObject.getString("dbegin"))) {
				dbegin = jsonObject.getString("dbegin");
			}

			String dend = null; //结束时间
			if (StringUtils.hasText(jsonObject.getString("dend"))) {
				dend = jsonObject.getString("dend");
			}

			List<Integer> steelgroup = null; // 钢种
			if (jsonObject.getJSONArray("steelgroup") != null) {
				steelgroup = jsonObject.getJSONArray("steelgroup");
			}

			Integer si_flag = null;
			if (jsonObject.getString("si_flag") != null) {
				si_flag = Integer.parseInt(jsonObject.getString("si_flag"));
			}

    		List<TbDsjRawcheckC621> list = tbDsjRawcheckC621Dao.findDataTbDsjRawcheckC621ByPage((pageIndex-1)*pageSize, pageIndex*pageSize,hot_coil_id,steelgrade,fin_grade,dbegin,dend,steelgroup,si_flag);
			Integer count = tbDsjRawcheckC621Dao.findDataTbDsjRawcheckC621ByPageSize(hot_coil_id,steelgrade,fin_grade,dbegin,dend,steelgroup,si_flag);
    		return ResultData.ResultDataSuccess(list, count);
        } catch (Exception e) {
        	e.printStackTrace();
        	return ResultData.ResultDataFaultSelf("查询失败,失败信息为" + e.getMessage(), null);
        }
    }

    /**
     * 根据主键查询单条记录
     * @param data 分页参数字符串
     */
    public ResultData findDataTbDsjRawcheckC621ByIndocno(String data) {
        try {
        	JTbDsjRawcheckC621 jtbDsjRawcheckC621 = JSON.parseObject(data, JTbDsjRawcheckC621.class);
        	Long indocno = jtbDsjRawcheckC621.getIndocno();

    		TbDsjRawcheckC621 tbDsjRawcheckC621 = tbDsjRawcheckC621Dao.findDataTbDsjRawcheckC621ByIndocno(indocno);
    		return ResultData.ResultDataSuccess(tbDsjRawcheckC621);
        } catch (Exception e) {
        	e.printStackTrace();
        	return ResultData.ResultDataFaultSelf("查询失败,失败信息为" + e.getMessage(), null);
        }
    }

	/**
	 * 查看记录
	 * @return list 对象集合返回
	 * */
	public List<TbDsjRawcheckC621> findDataTbDsjRawcheckC621(){
		List<TbDsjRawcheckC621> list = tbDsjRawcheckC621Dao.findDataTbDsjRawcheckC621();
		return list;
	}

    @Override
    public ResultData findDataByHotVolumeNos(JSONObject json) {
		JSONArray jsonArray = json.getJSONArray("volumeNos");
		List<String> volumeNos = jsonArray.toJavaList(String.class);
		if (CollectionUtils.isEmpty(volumeNos)) {
			return ResultData.ResultDataFaultSelf(null, "传入卷号为空");
		}

		Map<String, Map<String, List<Double>>> map = new HashMap<>();
		Query query1 = new Query(Criteria.where("volumeNo").in(volumeNos));
		List<QmsCurveDataMongo> list = mongoTemplate.find(query1, QmsCurveDataMongo.class);

		for (QmsCurveDataMongo qmsCurveDataMongo : list) {
			Map<String, List<Double>> mapValue = new HashMap<>();
//            Query query=new Query(Criteria.where("extid").is(no));
//            JDataSave621 jDataSave621 = mongoTemplate.findOne(query, JDataSave621.class);
			List<Double> list1 = qmsCurveDataMongo.getOriginBolg().get("hsm_fdh_thk_cold");
			List<Double> list2 = qmsCurveDataMongo.getOriginBolg().get("hsm_fdw_width_cold");
			List<Double> list3 = qmsCurveDataMongo.getOriginBolg().get("hsm_crown_c40");
			List<Double> list4 = qmsCurveDataMongo.getOriginBolg().get("hsm_flatness_wedge40");
			List<Double> list5 = qmsCurveDataMongo.getOriginBolg().get("hsm_fdt_fdt");
			List<Double> list6 = qmsCurveDataMongo.getOriginBolg().get("hsm_ctc_ct_temp");
			List<Double> list7 = qmsCurveDataMongo.getOriginBolg().get("hsm_flatness_symmetric_flatness");
			List<Double> list8 = qmsCurveDataMongo.getOriginBolg().get("hsm_flatness_asymmetric_flatness");

			mapValue.put("hsm_fdh_thk_cold", list1);
			mapValue.put("hsm_fdw_width_cold", list2);
			mapValue.put("hsm_crown_c40", list3);
			mapValue.put("hsm_flatness_wedge40", list4);
			mapValue.put("hsm_fdt_fdt", list5);
			mapValue.put("hsm_ctc_ct_temp", list6);
			mapValue.put("hsm_flatness_symmetric_flatness", list7);
			mapValue.put("hsm_flatness_asymmetric_flatness", list8);

			String volumeNo = qmsCurveDataMongo.getVolumeNo();
			if (StringUtils.hasText(volumeNo)) {
				map.put(volumeNo, mapValue);
			}
		}
		if (!CollectionUtils.isEmpty(map)) {
			return ResultData.ResultDataSuccess(map);
		}
		return ResultData.ResultDataFaultSelf(null, "查询数据为空");
    }

	@Override
	public void export(JSONObject jsonObject, HttpServletResponse response) {
		// 接收传入参数
		Integer pageSize = jsonObject.getInteger("pageSize");
		Integer pageCount = jsonObject.getInteger("pageCount");
		String fileNames = jsonObject.getString("fileName");
		JSONObject condition = jsonObject.getJSONObject("condition");

		String hot_coil_id = null;//热卷号
		if (!StringUtils.isEmpty(condition.get("hot_coil_id"))) {
			hot_coil_id = condition.get("hot_coil_id").toString();
		}
		String steelgrade = null;//钢牌号
		if (!StringUtils.isEmpty(condition.get("steelgrade"))) {
			steelgrade = condition.get("steelgrade").toString();
		}
		String fin_grade = null;//等级
		if (!StringUtils.isEmpty(condition.get("fin_grade"))) {
			fin_grade = condition.get("fin_grade").toString();
		}


		String dbegin = null; //开始时间
		if (StringUtils.hasText(condition.getString("dbegin"))) {
			dbegin = condition.getString("dbegin");
		}

		String dend = null; //结束时间
		if (StringUtils.hasText(condition.getString("dend"))) {
			dend = condition.getString("dend");
		}

		List<Integer> steelgroup = null; // 钢种
		if (condition.getJSONArray("steelgroup") != null) {
			steelgroup = condition.getJSONArray("steelgroup");
		}

		Integer si_flag = null;
		if (condition.getString("si_flag") != null) {
			si_flag = Integer.parseInt(condition.getString("si_flag"));
		}

		// 创建表格数据集合
		List<TbDsjRawcheckC621> listExcel = new ArrayList<>();

		// 调用service查询出数据
		List<TbDsjRawcheckC621> data = null;
		for (int i = 1; i <= pageCount; i++) {
			// 分页去数据库查询数据 这里可以去数据库查询每一页的数据
			data = tbDsjRawcheckC621Dao.findDataTbDsjRawcheckC621ByPage((i - 1) * pageSize, i * pageSize, hot_coil_id,steelgrade,fin_grade,dbegin,dend,steelgroup,si_flag);
			for (TbDsjRawcheckC621 item : data) {
				listExcel.add(item);
			}
		}
		// 判断service查询出的数据集合data是否为空
		if (CollectionUtils.isEmpty(listExcel)) {
			return;
		}
		List<ExportTbDsjRawcheckC621> list = new ArrayList<>();
		for (TbDsjRawcheckC621 item : listExcel) {
			ExportTbDsjRawcheckC621 exportTbDsjRawcheckC621 = new ExportTbDsjRawcheckC621();
			BeanUtils.copyProperties(item,exportTbDsjRawcheckC621);
			list.add(exportTbDsjRawcheckC621);
		}
		try {
			String classpath = null;
			if(si_flag==0)
			{
				classpath="classpath:exceltemplate\\1720原料库审核--非硅钢.xlsx";
			}
			if(si_flag==1)
			{
				classpath="classpath:exceltemplate\\1720原料库审核--硅钢.xlsx";
			}
			Map<String,Object> data1 = new HashMap();
			data1.put("data",list);
			File file = ResourceUtils.getFile(classpath);
			TemplateExportParams templateExportParams = new TemplateExportParams(file.getPath(),false);
			templateExportParams.setDictHandler(new PlanExcelHandlerImpl());
			Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, data1);
			ExcelUtilsPOI.exportExcel(fileNames,response,workbook);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}


}
